package com.jfinal.plugin.sqlxml;

import com.jfinal.plugin.IPlugin;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * 把sql放进xml的插件。
 * @author tangyang
 */
public class SqlXmlPlugin implements IPlugin {
    
    static boolean debug=false;
    
    private String dirPath;
    
    static DocumentBuilder documentBuilder;

    static {//调用jdk自己的xml解析，不想多加依赖。
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            documentBuilder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            throw new SqlXmlException("I don`t know .", ex);
        }
    }

    @Override
    public boolean start() {
        File file=new File(dirPath);
        boolean isdDirectory = file.isDirectory();
        if(isdDirectory){
            File[] xmlFiles = file.listFiles(new FileFilter() {
                
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".xml");
                }
            });
            for (File xmlFile : xmlFiles) {
                loadAXml(xmlFile);
            }
        }
        
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
    
    /**
     *  从目录中加载xml，其中只会检索以.xml结尾的文件，遇到非Mapper作为根节点的文件直接忽略
     * @param dirPath 为了您不搞错，请使用绝对地址，请自行使用PathKit获取所需地址
     */
    public void loadFromDir(String dirPath){
        this.dirPath=dirPath;
    }
    private void startDebugMode(){
        debug=true;
    }
    private void loadAXml(File xmlFile){
        
        Document document;
        try {
            document = documentBuilder.parse(xmlFile);
        } catch (SAXException ex) {
            return ;
        } catch (IOException ex) {
            return ;
        }
        if(document.getDocumentElement().getTagName().equals("Mapper")){
            XmlDaoBeanCreator creator = new XmlDaoBeanCreator();//创建该xml对应的bean
            creator.xmlToBean(document);
        }
    }
}
